
#import "PUWebViewVC.h"
#import <sys/utsname.h>
#import <objc/runtime.h>
#import <WebKit/WebKit.h>
#import "PUWKWebView.h"
#import <JavaScriptCore/JavaScriptCore.h>


@interface PUWebViewVC ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
@property (nonatomic, strong) UIProgressView *progressView;
@property (nonatomic, strong) WKWebView *webView;

@end

@implementation PUWebViewVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=self.titleStr;
    self.view.backgroundColor=[UIColor colorWithHex:0xfbf9fe];
    
    UIView *butV = [[UIView alloc] initWithFrame:CGRectMake(-20, 0, 50, 40)];
    UIImageView *imV = [[UIImageView alloc] initWithFrame:CGRectMake(0, 10, 20, 20)];
    imV.image = [UIImage imageNamed:@"backBtn"];
    [butV addSubview:imV];
    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
    leftButton.frame = CGRectMake(0, 0, 50, 40);
    [butV addSubview:leftButton];
    [leftButton addTarget:self action:@selector(LeftClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:butV];
        
    //应用于 ajax 请求的 cookie 设置
    WKUserContentController *userContentController = WKUserContentController.new;
    NSString *cookieSource = [NSString stringWithFormat:@"document.cookie = 'authorization=%@;path=/'",[Config getToken]];

    WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:cookieSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
    
    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    configuration.userContentController = userContentController;
    
    WKPreferences *preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    //    preferences.minimumFontSize = 30.0;
    preferences.minimumFontSize = 0.0f;
    configuration.preferences = preferences;
    
    self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    // 设置滚动速度
    self.webView.scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;
    // 设置不能上下回弹效果
    //    self.webView.scrollView.bounces=NO;
    self.webView.scrollView.alwaysBounceVertical = NO;
    [self.view addSubview:self.webView];
    
    int h=0;
    if(self.isXYEnter==1){
        h=STATUS_H_F+44;
    }
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(h);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
        make.bottom.equalTo(self.view.mas_bottom).offset(0);
    }];
    
    
    self.webView.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //进度条初始化
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, h, [[UIScreen mainScreen] bounds].size.width, 2)];
    self.progressView.backgroundColor = [UIColor blueColor];
    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    [self.view addSubview:self.progressView];
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    
    //    self.edgesForExtendedLayout = UIRectEdgeTop;
    if (@available(iOS 11.0, *)) {
        self.webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
//    dispatch_async(dispatch_get_main_queue(), ^{
//        //       [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.url]]];
//
//        NSURL *url=[NSURL URLWithString:self.url];
//        NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
//        [self.webView loadRequest:request];
//    });
    
    
    NSSet *websiteDataTypes = [NSSet setWithArray:@[
//                                                    WKWebsiteDataTypeDiskCache,
//                                                    WKWebsiteDataTypeMemoryCache,
                                                    //WKWebsiteDataTypeOfflineWebApplicationCache,
                                                    //WKWebsiteDataTypeLocalStorage,
                                                    //WKWebsiteDataTypeCookies,
                                                    //WKWebsiteDataTypeSessionStorage,
                                                    //WKWebsiteDataTypeIndexedDBDatabases,
                                                    //WKWebsiteDataTypeWebSQLDatabases
                                                    ]];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
        NSURL *url=[NSURL URLWithString:self.url];
        NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
        [self.webView loadRequest:request];
    }];
    
}


- (void)dealloc {
    [self removeScriptMessageHandlerForName];
}

-(void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
//    self.webView=nil;
    self.webView.UIDelegate=nil;
    self.webView.navigationDelegate=nil;
//    [self.navigationController setNavigationBarHidden:YES animated:NO];
}
-(void)removeScriptMessageHandlerForName{
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"closeWebView"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"getNativeToken"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"is_topbar"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"myBlogList"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"toPersonInfo"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"openPage"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"savePicture"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"getUserInfo"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"imageShare"];
    
}
-(void)addScriptMessageHandler{
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"closeWebView"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"getNativeToken"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"is_topbar"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"myBlogList"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"toPersonInfo"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"openPage"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"savePicture"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"getUserInfo"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"imageShare"];
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self removeScriptMessageHandlerForName];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if (self.is_topbar==1) {
        [self.navigationController setNavigationBarHidden:YES animated:YES];
    }else{
        [self.navigationController setNavigationBarHidden:NO animated:YES];
    }
    
    //禁用IQKeyboardManager
//    IQKeyboardManager *keyboardManager =  [IQKeyboardManager sharedManager];
//    keyboardManager.enable = NO;
//    keyboardManager.enableAutoToolbar = NO;
    
    if(self.isXYEnter!=1){
        // 设置导航条及状态栏的背景色
    //    self.navigationController.navigationBar.barTintColor = navigationBGColor;
        self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
        // 关闭导航条的透明效果
        self.navigationController.navigationBar.translucent = NO;
    }
    
    self.webView.UIDelegate=self;
    self.webView.navigationDelegate=self;
    [self addScriptMessageHandler];
  
}
-(void)LeftClick{
    if (self.isfirstEnter==1) {
        [self dismissViewControllerAnimated:NO completion:nil];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}

//在监听方法中获取网页加载的进度，并将进度赋给progressView.progress
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1) {
            /*
             *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
             *动画时长0.25s，延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
            __weak typeof (self)weakSelf = self;
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
                
            }];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
#pragma mark- WKNavigationDelegate
-(void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation

{
    
    //allWebsiteDataTypes清除所有缓存
//        NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
//        NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
//        [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
//
//        }];
    
    
    
    //    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSLog(@"webView.URL:%@", webView.URL);
    NSLog(@"开始加载网页");
    //开始加载网页时展示出progressView
    self.progressView.hidden = NO;
    //开始加载网页的时候将progressView的Height恢复为1.5倍
    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
    //防止progressView被网页挡住
    [self.view bringSubviewToFront:self.progressView];
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    //    [MBProgressHUD hideHUDForView:self.view animated:YES];
    NSLog(@"加载完成");
    //加载完成后隐藏progressView
    self.progressView.hidden = YES;
    NSLog(@"webView.URL:%@", webView.URL);
    NSLog(@"标题:%@",self.webView.title);
    
    //     [NSThread sleepForTimeInterval:1.0];//设置启动页面时间
    //    if ([self isBlankView:self.webView]) {
    ////        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.strUrl]]];
    //        NSLog(@"可能白屏");
    ////        NSURL *url=[NSURL URLWithString:self.strUrl];
    ////        NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    ////        [self.webView loadRequest:request];
    //    }
}
- (void)webView:(WKWebView *) webView didFailProvisionalNavigation: (WKNavigation *) navigation withError: (NSError *) error
{
    NSLog(@"加载失败");
    [self showSVProgressHUDStr:@"加载失败"];
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
}
- (void)webView: (WKWebView *)webView didFailNavigation:(WKNavigation *) navigation withError: (NSError *) error
{
    NSLog(@"加载失败");
    [self showSVProgressHUDStr:@"加载失败"];
    //加载失败同样需要隐藏progressView
    self.progressView.hidden = YES;
}
//JS调用alert()函数的代理 不实现这个方法JS调用alert()方法无效
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    [alerController addAction:cancelAction];
    
    [self presentViewController:alerController animated:YES completion:^{
        completionHandler();
        
    }];
}
//JS调用confirm()函数的代理，不实现这个方法JS调用confirm()无效
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
{
    UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"需要确认" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //回传用户的确认结果
        completionHandler(NO);
        
    }];
    
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //回传用户的确认结果
        completionHandler(YES);
        
    }];
    
    [alerController addAction:cancelAction];
    [alerController addAction:confirmAction];
    
    [self presentViewController:alerController animated:YES completion:^{
        
    }];
    
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        
        NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
        
        completionHandler(NSURLSessionAuthChallengeUseCredential,card);
        
    }
}
//h5调用ios
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
   
}

-(void)clickedLink:(NSString*)link title:(NSString *)title isLunBo:(int)isLunBo{
  
    PUWebViewVC *VC = [[PUWebViewVC alloc] init];
    if (isLunBo==1) {
        NSString *is_topbar=[self is_topbar:[self linkStr:link]];
        if ([is_topbar isEqualToString:@"1"]) {
            VC.is_topbar=0;//显示导航栏
        }else{
            VC.is_topbar=1;//隐藏导航栏
        }
        
    }else{
        VC.is_topbar=1;//隐藏导航栏
    }
    VC.url=[self linkStr:link];
    VC.titleStr=title;
    [self.navigationController pushViewController:VC animated:YES];
}

-(NSString *)is_topbar:(NSString*)yhxylink{
    NSString *is_topbar=@"";
    if ([yhxylink containsString:@"is_topbar"]) {
        if([[NSString stringWithFormat:@"%@",yhxylink] rangeOfString:@"&"].location != NSNotFound) {
            NSArray *array = [yhxylink componentsSeparatedByString:@"&"];
            for (NSString *str in array) {
                if ([str containsString:@"is_topbar"]) {
                    is_topbar=str;
                }
            }
            if (![is_topbar isEqualToString:@""]) {
                NSArray *array = [is_topbar componentsSeparatedByString:@"="];
                NSString *is_topbar2=array[1];
                is_topbar=is_topbar2;
            }
            NSLog(@"%@",is_topbar);
        }
    }
    return is_topbar;
}
-(NSString *)linkStr:(NSString*)yhxylink{
    NSString *app_Name = @"huatang";
    NSString *version=[self getVersion];
    NSString *sys=@"ios";
    
    if ([yhxylink containsString:@"?"]) {
        app_Name = [app_Name stringByRemovingPercentEncoding];
        yhxylink=[yhxylink stringByAppendingFormat:@"&cn_name=%@",app_Name];
        yhxylink = [yhxylink stringByRemovingPercentEncoding];
    }
    yhxylink = [yhxylink stringByReplacingOccurrencesOfString:@"{app_name}" withString:app_Name];
    yhxylink = (NSString*) CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,                                                 (CFStringRef)yhxylink,(CFStringRef)@"!$&'()*+,-./:;=?@_~%#[]",NULL, kCFStringEncodingUTF8));
    
    
    NSString *yhxylinkStr=@"webview://";
    if ([yhxylink containsString:@"webview://"]) {
        yhxylink =  [yhxylink substringWithRange:NSMakeRange(yhxylinkStr.length, yhxylink.length-yhxylinkStr.length)];
    }
   
    return yhxylink;
}
-(NSString *)getVersion{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *version=[NSString stringWithFormat:@"%@",[infoDictionary objectForKey:@"CFBundleShortVersionString"]];
    return version;
}
//图片保存后在回调方法 (系统自带的)
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error) {
        [self showSVProgressHUDStr:@"图片已经保存到相册!"];
    }
    else
    {
        [self showSVProgressHUDStr:@"图片保存失败!"];
    }
    
}
-(void)showSVProgressHUDStr:(NSString *)str{
    if ([str isKindOfClass:[NSNull class]]||str==nil||[str isEqualToString:@""]) {
        return;
    }
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD showImage:[UIImage imageNamed:@""] status:str];
}

-(void)CPPDTHViewSelectIndex:(int)index{

    
}


-(void)quick_FK:(NSNotification *)notification{
    if ([[self currentViewController] isKindOfClass:[PUWebViewVC class]]) {
        
    }
}


//用户充值协议
-(void)JMKBuyViewuserAgreement{
    NSDictionary *info_api = [Config getLaunch_api];
    NSArray *recharge_bottom=info_api[@"recharge_bottom"];
    if (recharge_bottom.count>1) {
        NSDictionary *dic=recharge_bottom[1];
        NSString *link=dic[@"link"];
        NSLog(@"%@",link);
        [self clickedLink:link title:@"用户充值协议"];
    }
}
-(void)clickedLink:(NSString*)link title:(NSString *)title{
    PUWebViewVC *VC = [[PUWebViewVC alloc] init];
    VC.url=[self linkStr:link];
    VC.titleStr=title;
    [self.navigationController pushViewController:VC animated:YES];
}

-(void)loadAppleCreateID:(int)ID{
    
}


#pragma mark IApRequestResultsDelegate
- (void)filedWithErrorCode:(NSInteger)errorCode andError:(NSString *)error {
   
}

-(void)appleZFSuccess{
//    NSString *coin=[NSString stringWithFormat:@"+%@",self.model.coin];
//    CPRechargeSuccessView *view =[[CPRechargeSuccessView alloc]initCPTipViewWithContent:coin title:@"充值成功" confirmStr:@"确定" cancelStr:@"返回修改" buttonCount:1 yyText:coin];
//    view.delegate=self;
//    [view show];
    [self showSVProgressHUDStr:@"购买成功"];
}


- (NSString *)getDeviceMsg{
    
    return @"";
}

//获取设备型号名称
- (NSString *)getDeviceModelName{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    if (!deviceString) return @"iPhone";
    //iPhone
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"Verizon iPhone 4";
    if ([deviceString isEqualToString:@"iPhone3,3"])    return @"iPhone 4";
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (GSM+CDMA)";
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5c (GSM)";
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5c (GSM+CDMA)";
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5s (GSM)";
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5s (GSM+CDMA)";
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    if ([deviceString isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    if ([deviceString isEqualToString:@"iPhone9,1"])    return @"iPhone 7"; //国行、日版、港行
    if ([deviceString isEqualToString:@"iPhone9,2"])    return @"iPhone 7 Plus"; //国行、港行
    if ([deviceString isEqualToString:@"iPhone9,3"])    return @"iPhone 7"; //美版、台版
    if ([deviceString isEqualToString:@"iPhone9,4"])    return @"iPhone 7 Plus"; //美版、台版
    if ([deviceString isEqualToString:@"iPhone10,1"])    return @"iPhone 8"; //国行(A1863)、日行(A1906)
    if ([deviceString isEqualToString:@"iPhone10,2"])    return @"iPhone 8 Plus"; //国行(A1864)、日行(A1898)
    if ([deviceString isEqualToString:@"iPhone10,3"])    return @"iPhone X"; //国行(A1865)、日行(A1902)
    if ([deviceString isEqualToString:@"iPhone10,4"])    return @"iPhone 8"; //美版(Global/A1905)
    if ([deviceString isEqualToString:@"iPhone10,5"])    return @"iPhone 8 Plus"; //美版(Global/A1897)
    if ([deviceString isEqualToString:@"iPhone10,6"])    return @"iPhone X";//美版(Global/A1901)
    if ([deviceString isEqualToString:@"iPhone11,8"])    return @"iPhone XR";
    if ([deviceString isEqualToString:@"iPhone11,2"])    return @"iPhone XS";
    if ([deviceString isEqualToString:@"iPhone11,6"])    return @"iPhone XS Max";
    if ([deviceString isEqualToString:@"iPhone11,4"])    return @"iPhone XS Max";
    if ([deviceString isEqualToString:@"iPhone12,1"])    return @"iPhone 11";
    if ([deviceString isEqualToString:@"iPhone12,3"])    return @"iPhone 11 Pro";
    if ([deviceString isEqualToString:@"iPhone12,5"])    return @"iPhone 11 Pro Max";
    if ([deviceString isEqualToString:@"iPhone12,8"])    return @"iPhone SE"; //(2nd generation)
    if ([deviceString isEqualToString:@"iPhone13,1"])    return @"iPhone 12 mini";
    if ([deviceString isEqualToString:@"iPhone13,2"])    return @"iPhone 12";
    if ([deviceString isEqualToString:@"iPhone13,3"])    return @"iPhone 12 Pro";
    if ([deviceString isEqualToString:@"iPhone13,4"])    return @"iPhone 12 Pro Max";
    if ([deviceString isEqualToString:@"iPhone14,2"])    return @"iPhone 13 Pro";
    if ([deviceString isEqualToString:@"iPhone14,3"])    return @"iPhone 13 Pro Max";
    if ([deviceString isEqualToString:@"iPhone14,4"])    return @"iPhone 13 mini";
    if ([deviceString isEqualToString:@"iPhone14,5"])    return @"iPhone 13";
    if ([deviceString isEqualToString:@"iPhone14,6"])    return @"iPhone SE"; //(2nd generation)
    if ([deviceString isEqualToString:@"iPhone14,7"])    return @"iPhone 14";
    if ([deviceString isEqualToString:@"iPhone14,8"])    return @"iPhone 14 Plus";
    if ([deviceString isEqualToString:@"iPhone15,2"])    return @"iPhone 14 Pro";
    if ([deviceString isEqualToString:@"iPhone15,3"])    return @"iPhone 14 Pro Max";
    
    if ([deviceString isEqualToString:@"iPhone15,4"])    return @"iPhone 15";
    if ([deviceString isEqualToString:@"iPhone15,5"])    return @"iPhone 15 Plus";
    if ([deviceString isEqualToString:@"iPhone16,1"])    return @"iPhone 15 Pro";
    if ([deviceString isEqualToString:@"iPhone16,2"])    return @"iPhone 15 Pro Max";
    
    //iPad
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([deviceString isEqualToString:@"iPad1,2"])      return @"iPad 3G";
    
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2";
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([deviceString isEqualToString:@"iPad2,4"])      return @"iPad 2";
    if ([deviceString isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
    if ([deviceString isEqualToString:@"iPad2,6"])      return @"iPad Mini";
    if ([deviceString isEqualToString:@"iPad2,7"])      return @"iPad Mini (GSM+CDMA)";
    
    if ([deviceString isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    if ([deviceString isEqualToString:@"iPad3,2"])      return @"iPad 3 (GSM+CDMA)";
    if ([deviceString isEqualToString:@"iPad3,3"])      return @"iPad 3";
    if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    if ([deviceString isEqualToString:@"iPad3,5"])      return @"iPad 4";
    if ([deviceString isEqualToString:@"iPad3,6"])      return @"iPad 4 (GSM+CDMA)";
    
    if ([deviceString isEqualToString:@"iPad4,1"])      return @"iPad Air (WiFi)";
    if ([deviceString isEqualToString:@"iPad4,2"])      return @"iPad Air (Cellular)";
    if ([deviceString isEqualToString:@"iPad4,3"])      return @"iPad Air";
    
    if ([deviceString isEqualToString:@"iPad4,4"])      return @"iPad Mini 2 (WiFi)";
    if ([deviceString isEqualToString:@"iPad4,5"])      return @"iPad Mini 2 (Cellular)";
    if ([deviceString isEqualToString:@"iPad4,6"])      return @"iPad Mini 2";
    
    if ([deviceString isEqualToString:@"iPad4,7"])      return @"iPad Mini 3";
    if ([deviceString isEqualToString:@"iPad4,8"])      return @"iPad Mini 3";
    if ([deviceString isEqualToString:@"iPad4,9"])      return @"iPad Mini 3";
    
    if ([deviceString isEqualToString:@"iPad5,1"])      return @"iPad Mini 4 (WiFi)";
    if ([deviceString isEqualToString:@"iPad5,2"])      return @"iPad Mini 4 (LTE)";
    if ([deviceString isEqualToString:@"iPad5,3"])      return @"iPad Air 2";
    if ([deviceString isEqualToString:@"iPad5,4"])      return @"iPad Air 2";
    
    if ([deviceString isEqualToString:@"iPad6,3"])      return @"iPad Pro 9.7";
    if ([deviceString isEqualToString:@"iPad6,4"])      return @"iPad Pro 9.7";
    if ([deviceString isEqualToString:@"iPad6,7"])      return @"iPad Pro 12.9";
    if ([deviceString isEqualToString:@"iPad6,8"])      return @"iPad Pro 12.9";
    
    if ([deviceString isEqualToString:@"iPad6,11"])     return @"iPad 5th";
    if ([deviceString isEqualToString:@"iPad6,12"])     return @"iPad 5th";
    
    if ([deviceString isEqualToString:@"iPad7,1"])      return @"iPad Pro 12.9 2nd";
    if ([deviceString isEqualToString:@"iPad7,2"])      return @"iPad Pro 12.9 2nd";
    if ([deviceString isEqualToString:@"iPad7,3"])      return @"iPad Pro 10.5";
    if ([deviceString isEqualToString:@"iPad7,4"])      return @"iPad Pro 10.5";
    
    if ([deviceString isEqualToString:@"iPad7,5"])      return @"iPad 6th";
    if ([deviceString isEqualToString:@"iPad7,6"])      return @"iPad 6th";
    
    if ([deviceString isEqualToString:@"iPad8,1"])      return @"iPad Pro 11";
    if ([deviceString isEqualToString:@"iPad8,2"])      return @"iPad Pro 11";
    if ([deviceString isEqualToString:@"iPad8,3"])      return @"iPad Pro 11";
    if ([deviceString isEqualToString:@"iPad8,4"])      return @"iPad Pro 11";
    
    if ([deviceString isEqualToString:@"iPad8,5"])      return @"iPad Pro 12.9 3rd";
    if ([deviceString isEqualToString:@"iPad8,6"])      return @"iPad Pro 12.9 3rd";
    if ([deviceString isEqualToString:@"iPad8,7"])      return @"iPad Pro 12.9 3rd";
    if ([deviceString isEqualToString:@"iPad8,8"])      return @"iPad Pro 12.9 3rd";
    
    if ([deviceString isEqualToString:@"iPad11,1"])      return @"iPad mini 5th";
    if ([deviceString isEqualToString:@"iPad11,2"])      return @"iPad mini 5th";
    if ([deviceString isEqualToString:@"iPad11,3"])      return @"iPad Air 3rd";
    if ([deviceString isEqualToString:@"iPad11,4"])      return @"iPad Air 3rd";
    
    if ([deviceString isEqualToString:@"iPad11,6"])      return @"iPad 8th";
    if ([deviceString isEqualToString:@"iPad11,7"])      return @"iPad 8th";
    
    if ([deviceString isEqualToString:@"iPad12,1"])      return @"iPad 9th";
    if ([deviceString isEqualToString:@"iPad12,2"])      return @"iPad 9th";
    
    if ([deviceString isEqualToString:@"iPad14,1"])      return @"iPad mini 6th";
    if ([deviceString isEqualToString:@"iPad14,2"])      return @"iPad mini 6th";
    
    //iPod
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([deviceString isEqualToString:@"iPod5,1"])      return @"iPod Touch (5 Gen)";
    if ([deviceString isEqualToString:@"iPod7,1"])      return @"iPod Touch (6 Gen)";
    if ([deviceString isEqualToString:@"iPod9,1"])      return @"iPod Touch (7 Gen)";
    
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    
    return deviceString;
}
/**
 响应链的方法
 */

- (UIViewController*)currentViewController{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    while (1)
    {
        //根据不同的页面切换方式，逐步取得最上层的viewController
        if ([vc isKindOfClass:[UITabBarController class]]) {
            vc = ((UITabBarController*)vc).selectedViewController;
        }
        if ([vc isKindOfClass:[UINavigationController class]]) {
            vc = ((UINavigationController*)vc).visibleViewController;
        }
        if (vc.presentedViewController) {
            vc = vc.presentedViewController;
        }else{
            break;
        }
    }
    return vc;
}

- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}
@end
